using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LiveStock.dataAccess;
using LiveStock.RssObjects;
using System.Net;
using LiveStock.Properties;
using LiveStock.Recommendation;
using System.Threading;


namespace LiveStock
{
    public partial class MainForm : FadeForm
    {
        //int CurrentUserID;  // Id of the current user using the app
        //int CurrentUserType; // UserType of the current user using the app
        Stock searchStock = new Stock(); //Stores the latest stock searched for, for use during a saveSearch
        CurrentUser curUser; // Current logged in user of the applicaiton.
        ListViewColumnSorter searchSorter; //Sorter for company search results, search tab.
        ListViewColumnSorter savedSorter; //Sorter for company search results, search tab.
        int numberOfCompanies = 0; //Stores the number of companies, in the case that a user adds a company
                                   // the list of saved companies should be remade with the new data, else
                                   // leave the list as it is.
        
        Boolean updateInProgress = false; //for prevents threads from being run at the same time.

        //Constructor
        public MainForm(CurrentUser current)
        {
            InitializeComponent();
            curUser = current;
            searchSorter = new ListViewColumnSorter();
            savedSorter = new ListViewColumnSorter();
            this.Search_lvCompSelect.ListViewItemSorter = searchSorter;
            this.Recom_lvSaved.ListViewItemSorter = savedSorter;
            //Set the name of the ManageUsers menu item based on UserType
            if (curUser.UserType == 1)
            {
                manageUsersToolStripMenuItem.Text = "My Account";
            }
            else { manageUsersToolStripMenuItem.Text = "User Management"; }
            //populate the saved companies list
            populateRecTab();
            if (Recom_lvSaved.Items.Count == 0)
            {
                MainTabs.SelectedIndex = 1;
                Search_txtCompanySearch.Focus();
            }
        }

        #region MainMenu

        private void manageUsersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ManageUser manage = new ManageUser(curUser);
            manage.Show();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox about = new AboutBox();
            about.Show();
        }

        private void livestockHelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Help.ShowHelp(this, "LiveStock.chm");
        }

        #endregion

        #region Search Tab

        private void fillResultBrowser(string stockSymbol)
        {
            searchStock = new Stock(stockSymbol);
            searchStock.UpdateFromMarket();

            HTMLTableCreator table = new HTMLTableCreator();
            if (searchStock.CompanyName != null)
            {               
                table.addRow("Description", searchStock.ToString());
                table.addRow("Company Name", searchStock.CompanyName);
                table.addRow("Stock Symbol", searchStock.StockSymbol);
                table.addRow("Exchange", searchStock.Exchange);
                table.addRow("Last Trade", searchStock.LastTrade.ToString());
                table.addRow("Change", searchStock.Change.ToString());
                table.addRow("Pct Change", searchStock.PctChange.ToString());
                table.addRow("Day Low", searchStock.DayLow.ToString());
                table.addRow("Day High", searchStock.DayHigh.ToString());
                table.addRow("Volume", searchStock.Volume);
                table.addRow("Timestamp", searchStock.LastUpdateDate.ToString());                
            }
            else
            {
                table.addRow("STOCK INFO", "No Matching Company Found");
            }
           
            Search_wbResultBrowser.DocumentText = table.createHTMLString(); 
            
        }

        private void alternateListColors(ListView lv)
        {
            if (lv.Items.Count > 0)
            {
                for (int i = 0; i < lv.Items.Count; i++)
                {
                    if (i % 2 != 0)
                    {
                        lv.Items[i].BackColor = Color.White;
                        lv.Items[i].ForeColor = Color.Black;
                    }
                    else
                        lv.Items[i].BackColor = Color.LightSteelBlue;
                        lv.Items[i].ForeColor = Color.Black;
                }
            }
        }

        private Boolean netConnCheck()
        {
            try
            {
                System.Uri URL = new Uri("http://www.finance.yahoo.com");
                WebRequest request = WebRequest.Create(URL);
                WebResponse response = request.GetResponse();
                response.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        private void Search_btnSearch_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            if (netConnCheck())
            {
                if (!Search_txtCompanySearch.Text.Equals(""))
                {
                    
                    CompanySearch search = new CompanySearch();
                    search.Lookup(Search_txtCompanySearch.Text);

                    if (search.companies != null)
                    {
                        
                        if (search.companies.Count == 1)
                        {
                            Search_lvCompSelect.Visible = false;
                            Search_lvCompSelect.Items.Clear();
                            fillResultBrowser(search.companies[0].StockSymbol);
                        }
                        else
                        {
                            Search_lvCompSelect.Visible = true;
                            Search_lvCompSelect.Items.Clear();
                            foreach (Stock s in search.companies)
                            {
                                string[] company = new string[] 
                            {
                                 s.StockSymbol,
                                 s.CompanyName,
                                 s.Exchange,
                                 s.Industry
                            };
                                ListViewItem item = new ListViewItem(company);

                                Search_lvCompSelect.Items.Add(item);
                            }
                            alternateListColors(Search_lvCompSelect);
                            Search_lvCompSelect.Focus();
                        }
                    }
                    else
                    {
                        MessageBox.Show("No Companies were found.", "No Matches.");
                    }
                }              
                else
                    MessageBox.Show("Nothing to search for.", "Search for what?", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                MessageBox.Show("Cannot Search\n\"Internet Connection Was Not Detected.\"", "No Connection.", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        private void Search_btnSave_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            if (!CompaniesData.CompanyAlreadySaved(searchStock.StockSymbol, curUser.UserID))
            {
                if (searchStock.CompanyName != null)
                {
                    
                    
                    try
                    {                        
                        Companies.CompaniesRow theCompaniesRow = new Companies.CompaniesDataTable().NewCompaniesRow();
                        theCompaniesRow.UserID = curUser.UserID;
                        theCompaniesRow.CompanyName = searchStock.CompanyName;
                        theCompaniesRow.Symbol = searchStock.StockSymbol;
                        theCompaniesRow.Exchange = searchStock.Exchange;
                        int companyID = CompaniesData.CompanyInsert(theCompaniesRow);
                    }
                    catch
                    {
                        MessageBox.Show("An Error occured while saving the company.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        
                    }
                    finally
                    {
                        //If the user selected the item from the list
                        //Remove the selected item, alternate the colors again
                        //If all companies are removed from the list, hide the list.
                        if (Search_lvCompSelect.SelectedItems.Count > 0)
                        {
                            Search_lvCompSelect.Items.RemoveAt(Search_lvCompSelect.SelectedItems[0].Index);
                            alternateListColors(Search_lvCompSelect);

                            if (Search_lvCompSelect.Items.Count == 0)
                            {
                                Search_lvCompSelect.Visible = false;
                            }
                        }
                        
                        //Clear the Result Browser (visually lets the user know that he/she has saved something)
                        Search_wbResultBrowser.DocumentText = searchStock.CompanyName + " was saved to your \"Saved Companies\" list.";

                        //Clear the searchStock
                        searchStock = new Stock();

                    }
                }
                else
                    MessageBox.Show("No Company To Save.", "Save Company", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }
            else
                MessageBox.Show("You already have that company saved.", "Already Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void Search_txtCompanySearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Search_btnSearch.Focus();
                Search_btnSearch.PerformClick();                
                e.Handled = true;
            }
        }

        private void Search_txtCompanySymbol_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Search_btnSearch.Focus();
                Search_btnSearch.PerformClick();
                e.Handled = true;
            }
        }
        
        private void Search_lvCompSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Search_lvCompSelect.SelectedItems.Count != 0)
            {
                alternateListColors(Search_lvCompSelect);
                try
                {
                    int intIndex = Search_lvCompSelect.SelectedItems[0].Index;
                    string t = Search_lvCompSelect.Items[intIndex].Text;
                    fillResultBrowser(t);
                }
                catch { }
            }
        }

        private void Search_txtCompanySearch_TextChanged(object sender, EventArgs e)
        {
            Search_lvCompSelect.Visible = false;
            if (Search_wbResultBrowser.DocumentText != "")
            { Search_wbResultBrowser.DocumentText = ""; }
        }

        private void Search_txtCompanySymbol_TextChanged(object sender, EventArgs e)
        {
            Search_lvCompSelect.Visible = false;
            if (Search_wbResultBrowser.DocumentText != "")
            { Search_wbResultBrowser.DocumentText = ""; }
        }

        private void Search_lvCompSelect_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // Determine if clicked column is already the column that is being sorted.
            if (e.Column == searchSorter.SortColumn)
            {
                // Reverse the current sort direction for this column.
                if (searchSorter.Order == SortOrder.Ascending)
                {
                    searchSorter.Order = SortOrder.Descending;
                }
                else
                {
                    searchSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                searchSorter.SortColumn = e.Column;
                searchSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.Search_lvCompSelect.Sort();
            alternateListColors(Search_lvCompSelect);
        }

        private void Search_lvCompSelect_Leave(object sender, EventArgs e)
        {
            if (Search_lvCompSelect.SelectedItems.Count > 0)
            {
                alternateListColors(Recom_lvSaved);
                Search_lvCompSelect.SelectedItems[0].BackColor = System.Drawing.Color.RoyalBlue;
                Search_lvCompSelect.SelectedItems[0].ForeColor = System.Drawing.Color.White;
            }
        }

        private void Search_lvCompSelect_KeyDown(object sender, KeyEventArgs e)
        {
            for (int i = 0; i < Search_lvCompSelect.Items.Count; i++)
            {

                if (Search_lvCompSelect.Items[i].SubItems[1].Text.StartsWith(e.KeyData.ToString()) || Search_lvCompSelect.Items[i].SubItems[1].Text.StartsWith(e.KeyData.ToString().ToLower()))
                {
                    Search_lvCompSelect.Items[i].Selected = true;
                    Search_lvCompSelect.Select();
                    Search_lvCompSelect.Items[i].EnsureVisible();
                    break;
                }
            }
        }

        #endregion

        #region Recommendation Tab

        private void Recom_lvSaved_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // Determine if clicked column is already the column that is being sorted.
            if (e.Column == savedSorter.SortColumn)
            {
                // Reverse the current sort direction for this column.
                if (savedSorter.Order == SortOrder.Ascending)
                {
                    savedSorter.Order = SortOrder.Descending;
                }
                else
                {
                    savedSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                savedSorter.SortColumn = e.Column;
                savedSorter.Order = SortOrder.Descending;
            }

            // Perform the sort with these new sort options.
            this.Recom_lvSaved.Sort();
            alternateListColors(Recom_lvSaved);
        }

        private void recomToGUI(int companyID, int recNum)
        {
            //Get RecomendationID, and Rating Type.
            Companies.CompaniesDataTable cdt = CompaniesData.CompanyGetByID(companyID);

            // Get the recommendations.
            Recommendations.RecommendationsDataTable rdt = RecommendationsData.RecommendationsGetByCompanyID(companyID);
            if (rdt.Rows.Count > 0)
            {
                int recentRecommendationID = rdt[recNum].RecommendationID;
                int ratingType = rdt[recNum].RatingTypeID;
                HTMLTableCreator recTable = new HTMLTableCreator();

                //Populate the DropdownList of past recommendations (includes most current recommendation).
                Recom_cboHistory.Items.Clear();
                for (int i = 0; i < rdt.Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        Recom_cboHistory.Items.Add("Current " + rdt[0].RecommendationDate);
                    }
                    else
                    {
                        Recom_cboHistory.Items.Add(rdt[i].RecommendationDate);
                    }

                }

                //Get Evaluations for the recommendation.
                Evaluations.EvaluationsDataTable edt = EvaluationsData.EvaluationsGetByRecommendationID(recentRecommendationID);

                //Get Evaluation Sources and create an html table bases on them.            
                for (int i = 0; i < edt.Rows.Count; i++)
                {
                    EvaluationSources.EvaluationSourcesDataTable esdt = EvaluationSourcesData.EvaluationSourceGetByID(edt[i].EvaluationSourceID);
                    recTable.addRow("Source", recTable.htmlLink(esdt[0].URL + cdt[0].Symbol, esdt[0].Name));
                    recTable.addRow("Title", edt[i].Title);
                    recTable.addRow("Link", recTable.htmlLink(edt[i].URL, ""));
                    recTable.addRow("Rating", edt[i].Rating.ToString());
                    recTable.addBlankRow();
                    recTable.addHorizontalLine();
                    recTable.addBlankRow();                  
                }

                //Set the browser text equal to the created table (function returns a html formatted table as a string)
                Recom_wbSources.DocumentText = recTable.createHTMLString();
                
                //Set the Recommendation graphic to the corresponding rating type.
                if (ratingType == 1)
                {
                    Recom_picRec.Image = Resources.Good;
                }
                else if (ratingType == 2)
                {
                    Recom_picRec.Image = Resources.InBetween;
                }
                else if (ratingType == 3)
                {
                    Recom_picRec.Image = Resources.Bad;
                }

                Recom_txtRatingNum.Text = "Overall Rating : " + rdt[recNum].Rating.ToString();
                //Format the GUI
                formatRecTabGUI(true);
                Recom_lnkPastRec.Visible = true;
                Recom_cboHistory.Visible = false;
            }
            else
            {
                Recom_lnkPastRec.Visible = false;
                Recom_cboHistory.Visible = false;
                if (updateInProgress == false)
                {
                    formatRecTabGUI(false);
                    Cursor.Current = Cursors.WaitCursor;
                    DialogResult r = MessageBox.Show("A Recomendation has not yet been made for this company\nWould you like to get one now?", "Get Recomendation?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (r == DialogResult.Yes)
                    {
                        if (netConnCheck())
                        {           

                            Recom_wbSources.DocumentText = "Getting a recommendation";
                            formatRecTabGUI(true);
                            GUIwhileUpdating(false);

                            updateInProgress = true;

                            CheckForIllegalCrossThreadCalls = false;
                            Thread update = new Thread(getFirstRec);
                            update.Start();
                        }
                        else
                        {
                            MessageBox.Show("Cannot Get Recommendaion\n\"Internet Connection Was Not Detected.\"", "No Connection.", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        }                       
                        
                    }
                }
            }
        }

        private void Recom_lvSaved_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Recom_lvSaved.SelectedItems.Count != 0)
            {
                alternateListColors(Recom_lvSaved);
                int intIndex = Recom_lvSaved.SelectedItems[0].Index;
                recomToGUI(Int32.Parse(Recom_lvSaved.Items[intIndex].Text), 0);

            }
        }

        private void getFirstRec()
        {
            Cursor.Current = Cursors.WaitCursor;
            int intIndex = Recom_lvSaved.SelectedItems[0].Index;
            Companies.CompaniesDataTable cdt = CompaniesData.CompanyGetByID(Int32.Parse(Recom_lvSaved.Items[intIndex].Text));
            RecommendationManager.ProcessRecommendation(cdt[0].CompanyID, cdt[0].Symbol, curUser.UserID, 0);
            int selIndex = Recom_lvSaved.SelectedIndices[0];
            Recom_lvSaved.Items[selIndex].Selected = false;
            Recom_lvSaved.Items[selIndex].Selected = true;

            updateInProgress = false;
            GUIwhileUpdating(true);
            if (Recom_lvSaved.SelectedItems.Count > 0)
            {
                alternateListColors(Recom_lvSaved);
                Recom_lvSaved.SelectedItems[0].BackColor = System.Drawing.Color.RoyalBlue;
                Recom_lvSaved.SelectedItems[0].ForeColor = System.Drawing.Color.White;
            }
        }

        private void updateRec()
        {
            Cursor.Current = Cursors.WaitCursor;
            int intIndex = Recom_lvSaved.SelectedItems[0].Index;
            Recommendations.RecommendationsDataTable rdt = RecommendationsData.RecommendationsGetByCompanyID(Int32.Parse(Recom_lvSaved.Items[intIndex].Text));
            if (rdt.Rows.Count > 0)
            {
                Companies.CompaniesDataTable cdt = CompaniesData.CompanyGetByID(Int32.Parse(Recom_lvSaved.Items[intIndex].Text));

                RecommendationManager.UpdateRecommendation(cdt[0].CompanyID, cdt[0].Symbol, curUser.UserID);
            }

            recomToGUI(Int32.Parse(Recom_lvSaved.Items[intIndex].Text), 0);
            GUIwhileUpdating(true);
            if (Recom_lvSaved.SelectedItems.Count > 0)
            {
                alternateListColors(Recom_lvSaved);
                Recom_lvSaved.SelectedItems[0].BackColor = System.Drawing.Color.RoyalBlue;
                Recom_lvSaved.SelectedItems[0].ForeColor = System.Drawing.Color.White;
            }
            
        }

        private void GUIwhileUpdating(Boolean isDoneUpdating)
        {
            Recom_picUpdate.Visible = !isDoneUpdating;
            Recom_picRec.Visible = isDoneUpdating;
            Recom_picReflect.Visible = isDoneUpdating;
            Recom_txtRatingNum.Visible = isDoneUpdating;
            Recom_lnkPastRec.Visible = isDoneUpdating;
            Recom_lnkPastRec.Enabled = isDoneUpdating;
            Recom_cboHistory.Enabled = isDoneUpdating;
            Recom_btnDelete.Enabled = isDoneUpdating;
            Recom_btnUpdate.Enabled = isDoneUpdating;
            Recom_lvSaved.Enabled = isDoneUpdating;
            Search_btnSearch.Enabled = isDoneUpdating;
            Search_btnSave.Enabled = isDoneUpdating;
            Search_txtCompanySearch.Enabled = isDoneUpdating;
            toolsToolStripMenuItem.Enabled = isDoneUpdating;
            helpToolStripMenuItem.Enabled = isDoneUpdating;
        }

        private void Recom_btnUpdate_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            if (Recom_lvSaved.SelectedItems.Count != 0)
            {
                
                //Only update/get recommendation if an internet connection is available.
                if (netConnCheck())
                {               
                    GUIwhileUpdating(false);
                    Recom_wbSources.DocumentText = "Updating/Getting a new Recommendation.";
                    CheckForIllegalCrossThreadCalls = false;
                    Thread update = new Thread(updateRec);
                    update.Start();              
                }
                else
                {
                    MessageBox.Show("Cannot Get Recommendaion\n\"Internet Connection Was Not Detected.\"", "No Connection.", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
            else
            {
                MessageBox.Show("No Company selected, cannot delete.", "No Company Selected", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void recommendationOptionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RecommendOption newRecommend = new RecommendOption(curUser);
            newRecommend.Show();
        }

        private void Recom_btnDelete_Click(object sender, EventArgs e)
        {
            if (Recom_lvSaved.SelectedItems.Count != 0)
            {
                DialogResult r = MessageBox.Show("Deleting a Saved Company will also delete\nall Recommendations associated with it.\nAre you sure you want to delete?", "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (r == DialogResult.Yes)
                {
                    int intIndex = Recom_lvSaved.SelectedItems[0].Index;
                    CompaniesData.CompanyDeleteByID(Int32.Parse(Recom_lvSaved.Items[intIndex].Text), curUser.UserID);
                    Recom_lvSaved.Items[intIndex].Remove();
                    alternateListColors(Recom_lvSaved);
                    formatRecTabGUI(false);

                    Companies.CompaniesDataTable cdt = CompaniesData.CompaniesGetByUserID(curUser.UserID);
                    numberOfCompanies = cdt.Count;

                    Recom_cboHistory.Visible = false;
                    if (Recom_wbSources.Visible)
                    {
                        Recom_lnkPastRec.Visible = true;
                    }
                    else
                    {
                        Recom_lnkPastRec.Visible = false;
                    }
                }
            }
            else
            {
                MessageBox.Show("No Company selected, cannot delete.", "No Company Selected", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void formatRecTabGUI(Boolean visible)
        {
            Recom_btnUpdate.Visible = visible;
            Recom_picRec.Visible = visible;
            Recom_picReflect.Visible = visible;
            Recom_txtRatingNum.Visible = visible;
            Recom_grpSources.Visible = visible;
            Recom_wbSources.Visible = visible;
            Recom_picUpdate.Visible = false;
            if (!Recom_wbSources.Visible)
            {
                Recom_wbSources.DocumentText = "";
            }
            if (Recom_cboHistory.Items.Count > 0)
            {
                if (Recom_lnkPastRec.Visible)
                {
                    Recom_lnkPastRec.Visible = !visible;
                    Recom_cboHistory.Visible = true;
                }
                else
                {
                    Recom_lnkPastRec.Visible = visible;
                    Recom_cboHistory.Visible = false;
                }

            }
            else
            {
                Recom_lnkPastRec.Visible = false;
                Recom_cboHistory.Visible = false;
            }
        }

        private void Recom_cboHistory_SelectedIndexChanged(object sender, EventArgs e)
        {
            int intIndex = Recom_lvSaved.SelectedItems[0].Index;
            recomToGUI(Int32.Parse(Recom_lvSaved.Items[intIndex].Text), Recom_cboHistory.SelectedIndex);
        }

        private void Recom_lnkPastRec_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Recom_cboHistory.Visible = true;
            Recom_cboHistory.Text = "Select a Date";
            Recom_lnkPastRec.Visible = false;
        }

        private void Recom_wbSources_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            //This makes sure that the users default browser is launched instead of IE all the time.
            if (e.Url.ToString().Equals("about:blank"))
            {
                //Do nothing                
            }
            else
            {
                e.Cancel = true;
                Recom_wbSources.Stop();
                System.Diagnostics.Process.Start(e.Url.ToString());

            }
        }

        private void Recom_lvSaved_Leave(object sender, EventArgs e)
        {
            if (Recom_lvSaved.SelectedItems.Count > 0)
            {
                alternateListColors(Recom_lvSaved);
                Recom_lvSaved.SelectedItems[0].BackColor = System.Drawing.Color.RoyalBlue;
                Recom_lvSaved.SelectedItems[0].ForeColor = System.Drawing.Color.White;
            }
        }

        private void populateRecTab()
        {
            //Create a companies data table, fill it with Companies for the current UserID
            Companies.CompaniesDataTable cdt = CompaniesData.CompaniesGetByUserID(curUser.UserID);
            if (cdt.Rows.Count > numberOfCompanies)
            {
                Recom_lvSaved.Items.Clear();

                for (int a = 0; a < cdt.Count; a++)
                {

                    string[] company = new string[] 
                            {
                                cdt[a].CompanyID.ToString(), cdt[a].CompanyName                                 
                            };
                    ListViewItem item = new ListViewItem(company);

                    Recom_lvSaved.Items.Add(item);
                }

                alternateListColors(Recom_lvSaved);
                numberOfCompanies = cdt.Rows.Count;
                Recom_lvSaved.Focus();
                formatRecTabGUI(false);
            }

            Recom_cboHistory.Visible = false;
            if (Recom_wbSources.Visible)
            {
                Recom_lnkPastRec.Visible = true;
            }
            else
            {
                Recom_lnkPastRec.Visible = false;
            }

        }

        private void Recom_lvSaved_KeyDown(object sender, KeyEventArgs e)
        {
            for (int i = 0; i < Recom_lvSaved.Items.Count; i++)
            {

                if (Recom_lvSaved.Items[i].SubItems[1].Text.StartsWith(e.KeyData.ToString()) || Recom_lvSaved.Items[i].SubItems[1].Text.StartsWith(e.KeyData.ToString().ToLower()))
                {
                    Recom_lvSaved.Items[i].Selected = true;
                    Recom_lvSaved.Select();
                    Recom_lvSaved.Items[i].EnsureVisible();
                    break;
                }
            }
        }

        #endregion

        #region MainForm Events

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {

            Application.Exit();
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }       

        private void MainTabs_Selected(object sender, TabControlEventArgs e)
        {

            if (MainTabs.SelectedTab == RecTab)
            {
                populateRecTab();
          
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            splitContainer1.SplitterDistance = 166;
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            splitContainer1.SplitterDistance = 166;

            Search_lvCompSelect.Columns[1].Width = 207 + (Search_lvCompSelect.Width - 418);
        }

        private void MainTabs_Enter(object sender, EventArgs e)
        {
            if (MainTabs.SelectedTab == RecTab)
            {
                if (Recom_lvSaved.Items.Count > 0 && Recom_lvSaved.SelectedItems.Count > 0)
                {
                    int selIndex = Recom_lvSaved.SelectedIndices[0];
                    Recom_lvSaved.Items[selIndex].Selected = false;
                    Recom_lvSaved.Items[selIndex].Selected = true;
                }
            }
        }

        #endregion   

        private void MainForm_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData.ToString().Equals("F2"))
            {
                MainTabs.SelectedTab = SearchTab;
                Search_txtCompanySearch.Focus();
            }

            if (e.KeyData.ToString().Equals("F1"))
            {
                MainTabs.SelectedTab = RecTab;
                Recom_lvSaved.Focus();
            }
        }

  

        
    }
}